package cybercode.carsaleserver.controller.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * 自定义过滤器，解决跨域请求的问题
 */
@Component
public class CorsFilter implements Filter {

    @Value("${cross-origin.enable}")
    private boolean enableCross;

    @Value("${cross-origin.prod}")
    private String prodUrl;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;


//        System.out.println("Request from: " + servletRequest.getRemoteHost());
//        System.out.println("Origin: " + request.getHeader("Origin"));

        if (!enableCross) {

            response.setHeader("Access-Control-Allow-Origin", prodUrl);
        } else {

            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        }

        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, No-Cache, X-Requested-With,Content-Type");
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST");
//        response.setHeader("Access-Control-Allow-Credentials", "true");


        filterChain.doFilter(servletRequest,response);
    }

    @Override
    public void destroy() {

    }
}
